package com.user.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.user.domain.User;


public class EmailUtils {

    public static void send(User user) {
        try {
            // 1 获得session
            Properties props = new Properties();
            //设置(外网)服务器
            props.setProperty("mail.host", "smtp.163.com");
            // 为防止被作为垃圾邮件处理，允许服务器进行强制校验
            props.setProperty("mail.smtp.auth", "true");
            Authenticator authenticator = new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    // 服务器中另外用户的账号和密码
                    return new PasswordAuthentication("xxx@xxx.com", "xxx");
                }
            };
            Session session = Session.getDefaultInstance(props, authenticator);
            // 2 message
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("xxx@xxx.com"));
            message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
            message.setSubject("祝福生日快乐");
            message.setContent("<h3 style='color:red'>尊敬的会员，祝您生日快乐！</h3>", "text/html;charset=UTF-8");

            // 3发送
            Transport.send(message);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
